package mi.payment.utils.transaction;

import android.content.Context;
import android.text.TextUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import mi.payment.constants.TransactionBitmap;
import mi.payment.utils.iso8583.EncodePackage;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.iso8583.Utils;
import mi.payment.utils.secure.TerminalSecure;
import sunmi.sunmiui.utils.LogUtil;

/**
 * 主密钥下载
 */
public class TMKDownloadTask extends TransactionTask<Void, Void, String> {

    protected TMKDownloadTask(Context c) {
        super(c, false);
    }

    @Override
    protected void onBegin(Void[] voids) {
    }

    @Override
    protected String appointResult() {
        return resultStr;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return EncodePackage.preAssemblyBase(TransactionBitmap.BITMAP_MTK_DOWNLOADED);
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        return EncodePackage.assembly(fieldMap, "0800", TerminalSecure.PROCESSREQUEST_NONE);
    }

    @Override
    protected void onUnpacked(HashMap<String, MsgField> resp) {
        if (TextUtils.equals("00", resultStr)) {
            MsgField f062_r = resp.get("F062");
            if (f062_r != null) {
                byte[] tmk = f062_r.getDataBytes();
                if (tmk.length > 16) {
                    tmk = Arrays.copyOf(f062_r.getDataBytes(), 16);
                }
                LogUtil.e(TAG, "tmk:" + Utils.byte2HexStr(tmk));
                int result = TerminalSecure.SaveTMK(tmk);
                if (result != 0) {
                    resultStr = "SF";
                }
            } else {
                resultStr = "FF";
            }
        } else if (TextUtils.equals("07", resultStr)) {
            resultStr = "F8";
        }
    }


}
